package com.example.Arithmetic.Lettcode;

/**
 * 日期：2023/10/14
 * 时间：17:26
 * 描述：设计双端循环队列，数组实现
 */
public class E05Lettcode641Array {
    int head;
    int tile;
    int[] in;

    public E05Lettcode641Array(int k) {
        in = new int[k + 1];
    }

    static int inc(int i, int length) {
        if (i + 1 >= length) {
            return 0;
        }
        return i + 1;
    }

    static int dec(int i, int length) {
        if (i - 1 < 0) {
            return length - 1;
        }
        return i - 1;
    }

    public boolean insertFront(int value) {
        if (isFull()) {
            return false;
        }
        head = dec(head, in.length);
        in[head] = value;
        return true;
    }

    public boolean insertLast(int value) {
        if (isFull()) {
            return false;
        }
        in[tile] = value;
        tile = inc(tile, in.length);
        return true;
    }

    public boolean deleteFront() {
        if (isEmpty()) {
            return true;
        }
        head = inc(head, in.length);
        return true;
    }

    public boolean deleteLast() {
        if (isEmpty()) {
            return false;
        }
        tile = dec(tile, in.length);
        return true;
    }

    public int getFront() {
        if (isEmpty()) {
            return -1;
        }
        return in[head];
    }

    public int getRear() {
        if (isEmpty()) {
            return -1;
        }
        return in[dec(tile, in.length)];
    }

    public boolean isEmpty() {
        return head == tile;
    }

    public boolean isFull() {
        if (tile > head) {
            return tile - head == in.length - 1;
        } else if (tile < head) {
            return head - tile == 1;
        } else {
            return false;
        }
    }
}
